
var app = getApp()
Page({
  data: {
    show: false,
    TabCur: 2,
    scrollLeft: 0,
    second_hand: [],
    lost_thing: [],
    have_pay: [],
    team: [],
    admin:false,
    challenge: [],
    download: [],
    currentList: [],//资料搜索结果
    searching: false,//空结果，
  },
  onLoad: function (options) {
    var id = options.id - 0
    this.setData({
      TabCur: id,
    })
    //console.log(id)
    switch (id) {
      case 0:
        //console.log('0')
        this.getFromDB('second_hand', 0)
        break;
      case 1:
        this.getFromDB('lost_thing', 0)
        break;
      case 2:
        this.getFromDB('have_pay', 0)
        break;
      case 3:
        this.getFromDB('team', 0)
        break;
      case 4:
        this.getFromDB('challenge', 0)
        break;
      case 5:
        this.getFromDB('download', 0)
        break;
    }
    qq.showShareMenu({
      showShareItems: ['qq', 'qzone', 'wechatFriends', 'wechatMoment']
    })
  },
  onReady() {
    this.setData({
      show: true,
      admin:app.globalData.admin
    })
  },
  toAdd(e){
    
    switch (this.data.TabCur) {
      case 0:
        qq.navigateTo({
          url: "/pages/tabBar2/add_second_hand/add_second_hand"
        })
        break;
      case 1:
        qq.navigateTo({
          url: "/pages/tabBar2/add_lost_thing/add_lost_thing"
        })
        break;
      case 2:
        qq.navigateTo({
          url: "/pages/tabBar2/add_have_pay/add_have_pay"
        })
        break;
      case 3:
        qq.navigateTo({
          url: "/pages/tabBar2/add_team/add_team"
        })
        break;
      case 4:
        qq.navigateTo({
          url: "/pages/tabBar2/add_challenge/add_challenge"
        })
        break;
      case 5:
        qq.navigateTo({
          url: "/pages/tabBar2/add_download/add_download"
        })
        break;
    }
  },
  deleteItem(e) {
    //console.log(e)
    var item = e.currentTarget.dataset.item
    var index = e.currentTarget.dataset.index
    //console.log(index)
    var that = this
    qq.showModal({
      title: '确定删除',
      content: '相关内容将会全部删除',
      success(res) {
        if (res.confirm) {
          var bar = ['second_hand', "lost_thing", "have_pay", "team", "challenge", "download"]
          var cur = that.data.TabCur
          switch (cur) {
            case 0:
              that.deleteDB(bar[cur], item._id, index)
              that.deleteComment(item._id)
              that.deleteImage(item.cloud_imageID)
              break;
            case 1:
            case 5:
              that.deleteDB(bar[cur], item._id,index)
              that.deleteImage(item.cloud_imageID)
              break;
            case 2:
            case 3:
            case 4:
              that.deleteDB(bar[cur], item._id,index)
              break;
          }
        }
      }
    })
  },
  deleteDB(collection, id, index) {
    var that = this
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databasedelete?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"" + collection + "\").doc(\"" + id + "\").remove()"
      },
      success(res) {
        that.refreshData(collection, index);
        qq.showToast({
          title: "删除成功"
        })
        //console.log(res)
      }
    })
  },
  refreshData(collection,index) {
    //console.log(index)
    switch (collection) {
      case 'second_hand':
        var second_hand = this.data.second_hand
        second_hand.splice(index, 1)
        this.setData({
          second_hand: second_hand
        })
        break;
      case 'lost_thing':
        var lost_thing = this.data.lost_thing
        lost_thing.splice(index, 1)
        this.setData({
          lost_thing: lost_thing
        })
        break;
      case 'have_pay':
        var have_pay = this.data.have_pay
        have_pay.splice(index, 1)
        this.setData({
          have_pay: have_pay
        })
        break;
      case 'team':
        var team = this.data.team
        team.splice(index, 1)
        this.setData({
          team: team
        })
        break;
      case 'challenge':
        var challenge = this.data.challenge
        challenge.splice(index, 1)
        this.setData({
          challenge: challenge
        })
        break;
      case 'download':
        var download = this.data.download
        download.splice(index, 1)
        this.setData({
          download: download
        })
        break;
    }

  },
  deleteComment(collection, id) {
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databasedelete?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"comment\").where({_itemId:\"" + id + "\"}).remove()"
      },
      success(res) {
        qq.showToast({
          title: "删除成功"
        })
        //console.log(res)
      }
    })
  },
  deleteImage(idList) {
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/batchdeletefile?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "fileid_list": idList
      },
      success(res) {
        qq.showToast({
          title: "删除成功"
        })
        //console.log(res)
      }
    })
  },
  search(e) {//资料页面的搜索
    // todo 只能搜索已经加载的，
    if (e.detail.value) {
      this.setData({
        searching: true
      })
    } else {
      this.setData({
        searching: false
      })
    }
    var list = this.data.download
    var t_list = []
    for (var i = 0; i < list.length; i++) {
      if (list[i].title.indexOf(e.detail.value) > -1) {
        t_list.push(list[i])
      }
    }
    if (t_list.length == 0) {
      this.getFromDB('download', list.length)//如果本地没有，则再请求
      this.setData({
        currentList: []
      })
    } else {
      this.setData({
        currentList: t_list
      })
    }
    //console.log(e.detail)
    //console.log(this.data.currentList)
  },
  detail_second_hand(e) {
    //console.log(e)
    wx.navigateTo({
      url: '/pages/tabBar2/detail_second_hand/detail_second_hand?item=' + JSON.stringify(e.currentTarget.dataset.item),
    })
  },
  downloadDetail(e) {
    qq.navigateTo({
      url: '/pages/tabBar2/detail_download/detail_download?item=' + JSON.stringify(e.currentTarget.dataset.item)
    })
    //console.log(e)
  },
  getFromDB(collection, skip) {
    qq.showLoading({
      title: '加载中'
    })
    var that = this
    var data =''
    if(this.data.admin){
 data={
        "env": app.globalData.myEnv,
        "query": "db.collection(\"" + collection + "\").limit(20).skip(" + skip + ").orderBy(\"publish_time\", \"desc\").get()"//管理端
      }
    }else{
      data = {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"" + collection + "\").where({_openid:\""+app.globalData.openid+"\"}).limit(20).skip(" + skip + ").orderBy(\"publish_time\", \"desc\").get()"
      }
    }
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databasequery?access_token=' + app.globalData.access_token,
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",

      data: data,
      success(res) {
        //console.log(res)
        var list = res.data.data //数组中的内容需要在下面转成对象
        qq.hideLoading()
        if (list.length > 0) {//如果没有请求完
          var newList = []
          for (var i = 0; i < list.length; i++) {
            newList[i] = JSON.parse(list[i])
          }
          // //console.log(newList)
          switch (that.data.TabCur) {
            case 0:
            case 1:
              that.getFileUrl(collection, newList)//需要加载图片的
              break;
            case 2:
            case 3:
            case 4:
              that.addList(collection, newList)//不需要加载图片的
              break;
            case 5:
              that.getAvgRate(collection, newList) //需要求平均评分
          }
        } else {//如果请求完了
          qq.showToast({
            title: '已加载全部'
          })
        }
      }
    })
  },
  getAvgRate(collection, list) {//传入的应该是数组对象，不是json
    for (var i = 0; i < list.length; i++) {
      var sum = 0;
      list[i].rateNum = list[i].rate.length
      for (var j = 0; j < list[i].rateNum; j++) {
        sum += list[i].rate[j];
      }
      // //console.log(sum,list[i].rate.length)
      list[i].avgRate = Math.floor((sum / list[i].rate.length) + 0.5)

      //console.log(list)
      //console.log(sum / list[i].rate.length)
    }
    this.addList(collection, list)
    //console.log("d")
  },
  getFileUrl(collection, list) {
    //console.log("ss")
    var that = this
    var now = 0;
    var newList = []
    for (var i = 0; i < list.length; i++) {
      (function () {
        var t = i
        var item = list[t]
        if (item.cloud_imageID) {
          var file_list_post = []//拼装file_list
          //console.log(item)
          for (var j = 0; j < item.cloud_imageID.length; j++) {
            file_list_post.push({
              "fileid": item.cloud_imageID[j],
              "max_age": 8640000
            })
          }
          qq.request({//请求拼装好的
            url: 'https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=' + app.globalData.access_token,
            header: {
              'content-type': 'application/json' // 默认值
            }, method: "post",
            data: {
              "env": app.globalData.myEnv,
              "file_list": file_list_post
            },
            success(res) {
              var file_list_return = res.data.file_list
              //console.log(res)
              var tempImageUrl = []
              for (var k = 0; k < file_list_return.length; k++) {
                tempImageUrl.push(file_list_return[k].download_url)
              }
              item.tempImageUrl = tempImageUrl
              newList[t] = item
              //console.log(newList)
              now++
            }
          })
        } else {
          now++
        }
      }(i))
    }
    var s = setInterval(function () {
      if (now == list.length) {
        //console.log(newList)
        that.addList(collection, newList)
        clearInterval(s)
      }
    })
  },
  restTime() {
    var setTime = new Date("2019-12-21 09:21")
  },
  addList(collection, list) {
    qq.stopPullDownRefresh()
    switch (collection) {
      case 'second_hand':
        this.setData({
          second_hand: this.data.second_hand.concat(list)
        })
        break;
      case 'lost_thing':
        this.setData({
          lost_thing: this.data.lost_thing.concat(list)
        })
        break;
      case 'have_pay':
        this.setData({
          have_pay: this.data.have_pay.concat(list)
        })
        break;
      case 'team':
        this.setData({
          team: this.data.team.concat(list)
        })
        break;
      case 'challenge':
        this.setData({
          challenge: this.data.challenge.concat(list)
        })
        break;
      case 'download':
        this.setData({
          download: this.data.download.concat(list)
        })
        break;
    }
  },

  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },


  previewImage(e) {
    //console.log(e)
    wx.previewImage({
      urls: e.currentTarget.dataset.imageurl,
      current: e.currentTarget.dataset.imageurl[0]
    });
  },



  onShareAppMessage: function () { },
  tabSelect(e) {//用户点击的，data中没有的情况下去请求数据，
    var id = e.currentTarget.dataset.id
    switch (id) {
      case 0:
        if (this.data.second_hand.length == 0) {
          //console.log("s")
          this.getFromDB('second_hand', 0)
        }
        break;
      case 1:
        if (this.data.lost_thing.length == 0) {
          //console.log('sd')
          this.getFromDB('lost_thing', 0)
        }
        break;
      case 2:
        if (this.data.have_pay.length == 0) {
          this.getFromDB('have_pay', 0)
        }
        break;
      case 3:
        if (this.data.team.length == 0) {
          this.getFromDB('team', 0)
        }
        break;
      case 4:
        if (this.data.challenge.length == 0) {
          this.getFromDB('challenge', 0)
        }
        break;
      case 5:
        if (this.data.download.length == 0) {
          this.getFromDB('download', 0)
        }
        break;
      case 6:
        if (this.data.institution.length == 0) {
          this.getFromDB('institution', 0)
        }
        break;
    }
    this.setData({
      TabCur: id - 0,
      scrollLeft: (id - 1) * 60
    })
  },


  onPullDownRefresh: function () {
    switch (this.data.TabCur) {
      case 0:
        this.setData({
          second_hand: []
        })
        this.getFromDB('second_hand', 0)
        break;
      case 1:
        this.setData({
          lost_thing: []
        })
        this.getFromDB('lost_thing', 0)
        break;
      case 2:
        this.setData({
          have_pay: []
        })
        this.getFromDB('have_pay', 0)
        break;
      case 3:
        this.setData({
          team: []
        })
        this.getFromDB('team', 0)
        break;
      case 4:
        this.setData({
          challenge: []
        })
        this.getFromDB('challenge', 0)
        break;
      case 5:
        this.setData({
          download: []
        })
        this.getFromDB('download', 0)
        break;
      case 6:
        this.setData({
          institution: []
        })
        this.getFromDB('institution', 0)
        break;
    }
  },
  onReachBottom: function () { // 已完成
    //console.log("bottom")
    switch (this.data.TabCur) {
      case 0:
        var skip = this.data.second_hand.length
        this.getFromDB('second_hand', skip)
        break;
      case 1:
        var skip = this.data.lost_thing.length
        this.getFromDB('second_hand', skip)
        break;
      case 2:
        var skip = this.data.have_pay.length
        this.getFromDB('have_pay', skip)
        break;
      case 3:
        var skip = this.data.team.length
        this.getFromDB('team', skip)
        break;
      case 4:
        var skip = this.data.challenge.length
        this.getFromDB('challenge', skip)
        break;
      case 5:
        var skip = this.data.download.length
        this.getFromDB('download', skip)
        break;
    }
  }
})